#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = ('api.rboyd@gmail.com (Ryan Boyd), '
              'alexandre.kunieda@gmail.com (Alexandre Kunieda)')

try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import time
import sys
sys.path.append('gdata-python-client')
import gdata.calendar.service
import gdata.calendar
import gdata.service
import atom.service
import atom

class CalendarSMS:

  def __init__(self, email, password):
    self.cal_client = gdata.calendar.service.CalendarService()
    self.cal_client.email = email
    self.cal_client.password = password
    self.cal_client.source = 'Pokes_SMS_sender'
    self.cal_client.ProgrammaticLogin()

  def _InsertEvent(self, title='', 
      content='', where='',
      email_list=[],
      send_event_notification='false'):
    event = gdata.calendar.CalendarEventEntry()
    event.title = atom.Title(text=title)
    event.content = atom.Content(text=content)
    event.where.append(gdata.calendar.Where(value_string=where))
    # Use current time for the start_time and have the event last 1 minute
    start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
    end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 60))
    event.when.append(gdata.calendar.When(start_time=start_time,
                                          end_time=end_time))

    for email in email_list:
      event.who.append(gdata.calendar.Who(email=email))
    event.send_event_notifications = gdata.calendar.SendEventNotifications(value=send_event_notification)

    while True:
      try:
        new_event = self.cal_client.InsertEvent(event,
               '/calendar/feeds/default/private/full')
        break
      except gdata.service.RequestError:
        time.sleep(60)  # ups, try again in 1 minute

    return new_event

  def _DeleteEvent(self, event):
    while True:
      try:
        self.cal_client.DeleteEvent(event.GetEditLink().href)
        break
      except gdata.service.RequestError:
        time.sleep(60)  # ups, try again in 1 minute

  def sendSMS(self, msg='', email_list=[], display_sms=True):
    if display_sms:
      print (msg)
    event = self._InsertEvent(title=msg,
                              email_list=email_list,
                              send_event_notification='true')
    self._DeleteEvent(event)


import unicodedata
def strip_accents(text, encoding):
  unicode_text = unicodedata.normalize('NFKD', text.decode(encoding))
  return filter(lambda x: not unicodedata.combining(x),
                unicode_text).encode(encoding)

def help():
  print ('Para utilizar este programa, execute:')
  print ('%s "[mensagem]" [emails]...') % sys.argv[0]
  sys.exit(1)


def sendSMS(msg='', email_list=[]):
  # break message, if necessary
  msg_list = []
  while len(msg) >= 61:
    msg_list.append(msg[:57] + '...')
    msg = msg[57:]
  msg_list.append(msg)

  # Google login and password
  user = 'alexandre.kunieda'
  pw = 'you wish... ;)'

  # dumb hack
  owner_email = user + '@gmail.com'
  try:
    email_list.remove(owner_email)
    owner = True
  except ValueError:
    owner = False # no match

  # login Google Calendar
  try:
    if email_list != []:
      obj = CalendarSMS(user, pw)
    if owner:
      obj_owner = CalendarSMS('alexandre.nk', 'you wish... ;)')
  except gdata.service.Error:
    print ('Problema no login')
    raise

  # generate events, sending SMS
  for msg in msg_list:
    if email_list != []:
      obj.sendSMS(msg=msg, email_list=email_list)
    if owner:
      obj_owner.sendSMS(msg=msg, email_list=[owner_email],
                        display_sms=(email_list == []))

  # display success!
  for email in email_list:
    print ('Enviado para %s') % email
  if owner:
    print ('Enviado para %s') % owner_email


def main():
  if len(sys.argv) < 3:
    help()

  # get message and email list
  msg = sys.argv[1]
  email_list = sys.argv[2:]

  # adjust message
  msg = msg.replace('\n', '; ').strip('; ')
  msg = strip_accents(msg.encode('utf-8'), 'utf-8')

  # send SMS!
  sendSMS(msg = msg, email_list = email_list)


if __name__ == '__main__':
  main()
